package com.zhangzy.qm.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.json.JSONObject;

import com.zhangzy.qm.dao.AblumDao;
import com.zhangzy.qm.dao.OptionDao;
import com.zhangzy.qm.dao.TopicDao;
import com.zhangzy.qm.entity.Ablum;
import com.zhangzy.qm.entity.Option;
import com.zhangzy.qm.entity.Topic;
import com.zhangzy.qm.util.Constants;
import com.zhangzy.qm.util.FileUtil;
import com.zhangzy.qm.util.HttpUtil;
import com.zhangzy.qm.util.ZipUtil;

public class TopicController {
	private HttpServletRequest request = ServletActionContext.getRequest();
	private HttpServletResponse response = ServletActionContext.getResponse();	
	private TopicDao topicDao;
	private AblumDao ablumDao;
	private OptionDao optionDao;
	private static final Logger logger = Logger.getLogger("ulog");
	public AblumDao getAblumDao() {
		return ablumDao;
	}

	public void setAblumDao(AblumDao ablumDao) {
		this.ablumDao = ablumDao;
	}

	public TopicDao getTopicDao() {
		return topicDao;
	}

	public void setTopicDao(TopicDao topicDao) {
		this.topicDao = topicDao;
	}
	
	public String toAddTopic(){
//		String hql = "from Ablum ab where ab.state=1";
		String hql = "from Ablum ab ";
		List<Ablum> list = ablumDao.query(hql);
		request.setAttribute("ablumList", list);
		return "addTopic";
	}
	public String toUpdateTopic(){
		int topicId = HttpUtil.getInt(request, "topicId",0);
		Topic t = new Topic();
		if(topicId!=0){
			try {
				t = (Topic) topicDao.getObjectById(Topic.class, topicId);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		request.setAttribute("topic", t);
		return "upateTopic";
	}
	public void doUpdateTopic(){
		int topicId = HttpUtil.getInt(request, "topicId",0);
		int gradeId = HttpUtil.getInt(request, "gradeId",0);
		int topicType = HttpUtil.getInt(request, "topicType",0);
		String remark = HttpUtil.getString(request, "remark","");
		String topicTitle = HttpUtil.getString(request, "topicTitle","");
		try {
			Topic t = (Topic) topicDao.getObjectById(Topic.class, topicId);
			if(t!=null){
				t.setGradeId(gradeId);
				t.setRemark(remark);
				t.setType(topicType);
				t.setTitle(topicTitle);
				topicDao.update(t);
				request.setAttribute("topic", t);
				
			}
			StringBuilder sb = new StringBuilder("{\"success\":\"true\"}");
			response.setContentType("text/html");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out= response.getWriter();
			out.println(sb.toString());
			out.flush();
			out.close();
			//generateZipFile(topicId);//生成zip文件
		} catch (Exception e) {
			e.printStackTrace();
		}		
		
	}

	public OptionDao getOptionDao() {
		return optionDao;
	}

	public void setOptionDao(OptionDao optionDao) {
		this.optionDao = optionDao;
	}
	
	public void doAddTopic() throws IOException{
		try {
			String title = HttpUtil.getString(request, "title","");
			String resourceUrl = HttpUtil.getString(request, "resourceUrl","");
			int type = HttpUtil.getInt(request, "type",0);
			int ablumId = HttpUtil.getInt(request, "ablumId",0);
			int gradeId = 0;
			int gradeType = HttpUtil.getInt(request, "ablumType",0);
			if(gradeType==1){//如果专辑类型是学院类
				gradeId=HttpUtil.getInt(request, "gradeId1",0);
			}else{
				gradeId=HttpUtil.getInt(request, "gradeId2",0);
			}
			String remark = HttpUtil.getString(request, "remark","");
			String optionNames = HttpUtil.getString(request, "optionNames","");
			String rightFlags = HttpUtil.getString(request, "rightFlags","");
			Topic topic = new Topic();
			topic.setTitle(title);
			topic.setResourceUrl(resourceUrl);
			topic.setType(type);
			topic.setRemark(remark);
			topic.setSaveTime(new Date());
			topic.setGradeId(gradeId);
			topic.setGradeType(gradeType);
			Ablum ab = new Ablum();
			ab.setId(ablumId);
			topic.setAblum(ab);
			Topic obj = (Topic) topicDao.save(topic);			
			StringBuilder sb = new StringBuilder("{\"success\":");
			if(obj!=null){
				String[] optionArray = optionNames.split(",");
				String[] flagArray = rightFlags.split(",");
				for(int i = 0; i<optionArray.length;i++){
					Option option = new Option();
					topic.setId(obj.getId());
					option.setTitle(optionArray[i]);
					option.setRightFlag(Integer.valueOf(flagArray[i]));
					option.setTopic(topic);
					option.setSaveTime(new Date());
					optionDao.save(option);				
				}
				sb.append("\"true\"}");
			}else{
				sb.append("\"false\"}");
			}
			response.setContentType("text/html");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out;		
			out = response.getWriter();
			out.println(sb.toString());
			out.flush();
			out.close();
			//generateZipFile(obj.getId());//生成zip文件
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public String topicIndex(){
		Map<String,String> params = new HashMap<String,String>();
		int ablumId = HttpUtil.getInt(request, "ablumId",0);
		int topicId = HttpUtil.getInt(request, "topicId",0);
		String title = HttpUtil.getString(request, "title","");
		String grade = HttpUtil.getString(request, "grade","");
		String remark = HttpUtil.getString(request, "remark","");
		int pageNum = HttpUtil.getInt(request, "page", 1);
		final int pageSize = HttpUtil.getInt(request, "pageSize", 20);		
		final int start = pageSize * (pageNum - 1);		
		params.put("title", title);
		params.put("grade", grade);
		params.put("remark", remark);		
		params.put("topicId", topicId+"");		
		params.put("ablumId", ablumId+"");		
		StringBuilder sql1 = new StringBuilder();
		StringBuilder sql2 = new StringBuilder();
		sql1.append("from Topic as t  where 1=1 ");
		sql2.append("select count(*) from Topic as t where 1=1 ");		
		if(!"".equals(title)){
			sql1.append("and t.title like '%"+title+"%' ");
			sql2.append("and t.title like '%"+title+"%' ");
		}
		if(!"-1".equals(grade)){
			if(grade.startsWith("9") && grade.length()>1){
				String tmp = grade.replace("9", "");
				sql1.append("and t.gradeId = '"+tmp+"' and (t.gradeType=2 or t.gradeType=3 )");			
				sql2.append("and t.gradeId = '"+tmp+"' and (t.gradeType=2 or t.gradeType=3 )");
			}else{
				sql1.append("and t.gradeId = '"+grade+"' and t.gradeType=1 ");			
				sql2.append("and t.gradeId = '"+grade+"' and t.gradeType=1 ");	
			}

		}
		if(!"".equals(remark)){
			sql1.append("and t.remark like '%"+remark+"%' ");			
			sql2.append("and t.remark like '%"+remark+"%' ");			
			
		}
		if(ablumId!=0){
			sql1.append(" and t.ablum.id="+ablumId);
			sql2.append(" and t.ablum.id="+ablumId);
		}
		if(topicId!=0){
			sql1.append(" and t.id="+topicId);
			sql2.append(" and t.id="+topicId);
		}
		sql1.append(" order by t.id desc ");
		List<Topic> dataList = new ArrayList<Topic>();
		try {
			dataList = topicDao.query(sql1.toString(),start,pageSize);
		} catch (Exception e) {
			e.printStackTrace();
		}
		int count = topicDao.queryCount(sql2.toString());
		
		String sql=" from Ablum ";
		List<Ablum> ablumList = ablumDao.query(sql);
		request.setAttribute("dataList", dataList);
		request.setAttribute("ablumList", ablumList);
		request.setAttribute("params", params);
		request.setAttribute("count", count);
		request.setAttribute("pageCount", (count - 1) / pageSize + 1);
		request.setAttribute("pageNum", pageNum);			
		request.setAttribute("pageSize", pageSize);			
		return "topicIndex";
	}
	
	public void removeTopic() throws Exception{
		int topicId = HttpUtil.getInt(request, "id",0);
		topicDao.removeObject(Topic.class, topicId);
		//generateZipFile(topicId);//生成zip文件
		response.sendRedirect(request.getContextPath()+"/topicIndex.action");
	}
	public void removeTopic2() throws Exception{
		int topicId = HttpUtil.getInt(request, "id",0);
		topicDao.removeObject(Topic.class, topicId);
		//generateZipFile(topicId);//生成zip文件
		StringBuilder sb = new StringBuilder("{\"success\":\"true\"}");
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out= response.getWriter();
		out.println(sb.toString());
		out.flush();
		out.close();
	}
	
	public String toAddOption() throws Exception{
		int topicId = HttpUtil.getInt(request, "topicId",0);
		int optionId = HttpUtil.getInt(request, "id",0);
		Topic topic = new Topic();
		Option option = new Option();
		if(topicId!=0){
			topic = (Topic) topicDao.getObjectById(Topic.class, topicId);
		}
		if(optionId!=0){
			option = (Option) optionDao.getObjectById(Option.class, optionId);
		}
		String sql="";
		if(topicId!=0){
			sql="select COALESCE(max(id),0) from Topic ";
			int maxId = topicDao.queryId(sql);
			sql="select COALESCE(min(id),0) from Topic";
			int minId = topicDao.queryId(sql);
			if(maxId==topicId){
				request.setAttribute("max", 1);
			}else if(minId==topicId){
				request.setAttribute("min", 1);
			}
		}
		sql = "SELECT COUNT(*) as value1,t.grade_id as key1 FROM t_topic t WHERE t.grade_type=1 and t.ablum_id="+topic.getAblum().getId()+" GROUP BY t.grade_id";
		Map<String,Integer> grade1 = topicDao.queryMap(sql);
		sql = "SELECT COUNT(*) as value1,t.grade_id as key1 FROM t_topic t WHERE t.grade_type!=1 and t.ablum_id="+topic.getAblum().getId()+" GROUP BY t.grade_id";
		Map<String,Integer> grade2 = topicDao.queryMap(sql);
		StringBuilder hql = new StringBuilder();
		hql.append("from Option o where o.topic.id=");
		hql.append(topicId);
		hql.append(" order by o.id desc");
		List<Option> dataList = optionDao.query(hql.toString());
		request.setAttribute("topic", topic);
		request.setAttribute("curOption", option);
		request.setAttribute("dataList", dataList);
		request.setAttribute("grade10", grade1.get("0"));
		request.setAttribute("grade11", grade1.get("1"));
		request.setAttribute("grade12", grade1.get("2"));
		request.setAttribute("grade13", grade1.get("3"));
		request.setAttribute("grade14", grade1.get("4"));
		request.setAttribute("grade15", grade1.get("5"));
		request.setAttribute("grade16", grade1.get("6"));
		request.setAttribute("grade17", grade1.get("7"));
		request.setAttribute("grade18", grade1.get("8"));
		request.setAttribute("grade19", grade1.get("9"));
		request.setAttribute("grade110", grade1.get("10"));
		request.setAttribute("grade111", grade1.get("11"));
		request.setAttribute("grade112", grade1.get("12"));
		request.setAttribute("grade113", grade1.get("13"));
		request.setAttribute("grade114", grade1.get("14"));
		request.setAttribute("grade115", grade1.get("15"));
		request.setAttribute("grade116", grade1.get("16"));
		request.setAttribute("grade117", grade1.get("17"));
		request.setAttribute("grade118", grade1.get("18"));
		request.setAttribute("grade119", grade1.get("19"));
		request.setAttribute("grade120", grade1.get("20"));
		request.setAttribute("grade121", grade1.get("21"));
		request.setAttribute("grade122", grade1.get("22"));
		request.setAttribute("grade123", grade1.get("23"));
		request.setAttribute("grade124", grade1.get("24"));
		request.setAttribute("grade125", grade1.get("25"));
		request.setAttribute("grade126", grade1.get("26"));
		request.setAttribute("grade127", grade1.get("27"));
		
		request.setAttribute("grade20", grade2.get("0"));
		request.setAttribute("grade21", grade2.get("1"));
		request.setAttribute("grade22", grade2.get("2"));
		request.setAttribute("grade23", grade2.get("3"));
		request.setAttribute("grade24", grade2.get("4"));
		request.setAttribute("grade25", grade2.get("5"));

		return "addOption";
	}
	
	public void addAndUpdateOption() throws Exception{
		int topicId = HttpUtil.getInt(request, "topicId",0);
		int optionId = HttpUtil.getInt(request, "id",0);		
		String title = HttpUtil.getString(request, "title","");
		int rightFlag = HttpUtil.getInt(request, "rightFlag",1);
		Topic topic = new Topic();
		if(optionId==0){
			Option option = new Option();
			topic.setId(topicId);
			option.setTitle(title);
			option.setRightFlag(rightFlag);
			option.setTopic(topic);
			option.setSaveTime(new Date());
			optionDao.save(option);
		}else{
			Option option = (Option) optionDao.getObjectById(Option.class, optionId);
			option.setTitle(title);
			option.setRightFlag(rightFlag);
			optionDao.update(option);
		}
		//generateZipFile(topicId);//生成zip文件
		response.sendRedirect(request.getContextPath()+"/toAddOption.action?topicId="+topicId);
	}
	
	public void removeOption() throws Exception{
		int optionId = HttpUtil.getInt(request, "id",0);	
		int topicId = HttpUtil.getInt(request, "topicId",0);
		optionDao.removeObject(Option.class, optionId);
		//generateZipFile(topicId);//生成zip文件
		response.sendRedirect(request.getContextPath()+"/toAddOption.action?topicId="+topicId);
	}
	
	public void toPreOption() throws Exception{
		int topicId = HttpUtil.getInt(request, "topicId",0);
		if(topicId!=0){			
			String sql = "select COALESCE(min(id),0) from Topic where id>"+topicId;
			int preId = topicDao.queryId(sql);
			response.sendRedirect(request.getContextPath()+"/toAddOption.action?topicId="+preId);
		}
	}
	public void toNextOption() throws Exception{
		int topicId = HttpUtil.getInt(request, "topicId",0);
		String sql = "";		
		if(topicId==0){
			sql="select COALESCE(max(id),0) from Topic ";
		}else{
			sql = "select COALESCE(max(id),0) from Topic where id<"+topicId;
		}
		int nextId = topicDao.queryId(sql);
		response.sendRedirect(request.getContextPath()+"/toAddOption.action?topicId="+nextId);
	}
	
	/**
	 * 生成zip文件
	 * @Methods Name generateZipFile
	 * @Create In Jul 15, 2012 By zhenyu
	 * @param topicId
	 * @return
	 * @throws Exception boolean
	 */
	private boolean generateZipFile(int topicId) throws Exception{
		List<Topic> topicList = new ArrayList<Topic> ();
		Topic t = (Topic) topicDao.getObjectById(Topic.class, topicId);
		int subjectId = t.getAblum().getId();
		try {
			if(subjectId!=0){
				String zipPath=Constants.zipPath+"/"+subjectId+"/"+subjectId+"/";//需要打包的专辑资源存放位置
				String zipSrcPath=zipPath+"/src/";//需要打包的专辑资源存放位置
				File f1 = new File(zipPath);
				if(!(f1.exists())){
					f1.mkdirs();
				}
				File f2 = new File(zipSrcPath);
				if(!(f2.exists())){
					f2.mkdirs();
				}
				Ablum ab = ablumDao.getAblum(subjectId);	
				String image="";
				if(ab.getImageUrl()!=null && !"".equals(ab.getImageUrl())){
					String urlValue = ab.getImageUrl();
					//初始化的图片的在特殊的文件里，要把路径替换掉
					if(urlValue.contains(Constants.uploadPath+"10001/") || urlValue.contains(Constants.uploadPath+"10002/") 
						|| urlValue.contains(Constants.uploadPath+"10003/") ||urlValue.contains(Constants.uploadPath+"10004/")
						|| urlValue.contains(Constants.uploadPath+"10005/") || urlValue.contains(Constants.uploadPath+"10006/")){
						urlValue = urlValue.replaceAll("10001/", "");
						urlValue = urlValue.replaceAll("10002/", "");
						urlValue = urlValue.replaceAll("10003/", "");
						urlValue = urlValue.replaceAll("10004/", "");
						urlValue = urlValue.replaceAll("10005/", "");
						urlValue = urlValue.replaceAll("10006/", "");
					}
					image = urlValue.replace(Constants.uploadPath, "src/");
					
					
					FileUtil.copy(ab.getImageUrl() , zipPath+image);//复制专辑封面
				}
				StringBuilder sb = new StringBuilder("{");
				sb.append("\"subjectId\":\""+ab.getId()+"\" , ");
				sb.append("\"subjectName\":\""+ab.getTitle()+"\" , ");
				sb.append("\"subjectType\":\"0"+ab.getType()+"\" , ");
				sb.append("\"subjectImage\":\""+image+"\" , ");
				sb.append("\"subjectInfo\":\""+ab.getRemark()+"\" , ");
				sb.append("\"paperList\":[");
				
				topicList = topicDao.query(" from Topic t where t.ablum.id="+ab.getId());
				Collections.shuffle(topicList); //打乱顺序
				int j =0;
				for(Topic topic:topicList){
					String qContent ="";
					if(topic.getType()==1){
						qContent=topic.getTitle();
					}else{
						qContent=topic.getResourceUrl();
						//初始化的图片的在特殊的文件里，要把路径替换掉
						if(qContent.contains(Constants.uploadPath+"10001/") || qContent.contains(Constants.uploadPath+"10002/") 
							|| qContent.contains(Constants.uploadPath+"10003/") ||qContent.contains(Constants.uploadPath+"10004/")
							|| qContent.contains(Constants.uploadPath+"10005/") || qContent.contains(Constants.uploadPath+"10006/")){
							qContent = qContent.replaceAll("10001/", "");
							qContent = qContent.replaceAll("10002/", "");
							qContent = qContent.replaceAll("10003/", "");
							qContent = qContent.replaceAll("10004/", "");
							qContent = qContent.replaceAll("10005/", "");
							qContent = qContent.replaceAll("10006/", "");
						}
						qContent = qContent.replace(Constants.uploadPath,"src/");
						FileUtil.copy(topic.getResourceUrl() , zipPath+qContent);//复制资源文件 
					}
					String subjectInfo = topic.getRemark();					
					List<Option> optionList = optionDao.query("from Option o where o.topic.id="+topic.getId());
					List<Option> resultList = new ArrayList<Option>();
					if(optionList!=null && (optionList.size()==2 || optionList.size()>=4)){//只有满足此条件才打包
						if(j!=0){
							sb.append(" , ");
						}
						sb.append("{");
						sb.append("\"questionId\":\""+topic.getId()+"\" , ");
						sb.append("\"questionType\":\"0"+topic.getType()+"\" , ");
						sb.append("\"subjectId\":\""+topic.getAblum().getId()+"\" , ");
						sb.append("\"questionContent\":\""+qContent+"\" , ");
						sb.append("\"subjectInfo\":\""+subjectInfo+"\" , ");
						sb.append("\"grade\":\""+topic.getGradeId()+"\" , ");
						for(Option option:optionList){
							if(option.getRightFlag()==1){
								resultList.add(option);
								optionList.remove(option);//此处删除是为了下面的逻辑随机取值时都取的为不正确的结果
								break;
							}
						}
						Collections.shuffle(optionList); //打乱顺序
						if(optionList.size()>0){
							resultList.add(optionList.get(0));
						}
						if(optionList.size()>1){
							resultList.add(optionList.get(1));
						}
						if(optionList.size()>2){
							resultList.add(optionList.get(2));
						}	
						if(resultList.size()==1){
							Option o1 = new Option();
							o1.setTitle("");
							Option o2 = new Option();
							o2.setTitle("");
							Option o3 = new Option();
							o3.setTitle("");
							resultList.add(o1);
							resultList.add(o2);
							resultList.add(o3);
						}else if(resultList.size()==3){
							Option o1 = new Option();
							o1.setTitle("");
							resultList.add(o1);
						}else if(resultList.size()==0){
							Option o1 = new Option();
							o1.setTitle("");
							Option o2 = new Option();
							o2.setTitle("");
							Option o3 = new Option();
							o3.setTitle("");
							Option o4 = new Option();
							o4.setTitle("");
							resultList.add(o1);
							resultList.add(o2);
							resultList.add(o3);
							resultList.add(o4);
						}
						Collections.shuffle(resultList); //打乱顺序 
						int i = 0;
						boolean tempFlag = false;
						for(Option option:resultList){
							String optionFlag = "option";
							if(i==0){
								optionFlag="A";
							}else if(i==1){
								optionFlag="B";
							}else if(i==2){
								optionFlag="C";
							}else if(i==3){
								optionFlag="D";
							}
							if(option.getRightFlag()==1){
								tempFlag=true;
								sb.append("\"option"+optionFlag+"\":\""+option.getTitle()+"\" , ");	
								sb.append("\"correctAnswer\":\""+optionFlag+"\" ");						
							}else{
								sb.append("\"option"+optionFlag+"\":\""+option.getTitle()+"\" ");				
							}
							if(i!=resultList.size()-1){
								sb.append(",");
							}					
							i++;
						}
						if(!tempFlag){//没有正确答案，默认A
							sb.append(",\"correctAnswer\":\"A\" ");		
						}
						if(resultList.size()==2){//只有两个选项，c,d 设置为空
							sb.append(",\"optionC\":\"\",\"optionD\":\"\"");	
						}				
						j++;
						sb.append("}");
					}				
			}
			sb.append("]");
			sb.append("}");	  
			FileUtil.writeFile(sb.toString(),zipPath+subjectId+".txt");//写json文件	
			ZipUtil.zip(Constants.zipPath+"/"+subjectId, Constants.zipPath+"/"+subjectId+".zip");		
			}
		} catch (Exception e) {
			logger.error(e.getStackTrace());
			return false;
		}
		return true;
	}
}
